//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入接口和数据类型
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type {
  loginFormData,
  loginResponseData,
  userInfoReponseData,
} from '@/api/user/type'
import type { UserState } from './types/type'
//引入操作本地存储的工具和方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入路由
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes'
import router from '@/router'
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'

//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

//创建用户小仓库
let useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户的唯一标识token
      menuRoutes: constantRoute, //生成菜单需要的数组
      username: '', //用户名
      avatar: '', //头像
      buttons: [], //当前用户是否包含某一个按钮
    }
  },
  actions: {
    //用户登录的方法
    async userLogin(data: loginFormData) {
      //登录请求
      let result: loginResponseData = await reqLogin(data)
      //登录请求：成功200->token
      //登录请求：失败201->登陆失败错误的信息
      if (result.code === 200) {
        //pinia仓库存储一下token
        this.token = result.data as string
        //由于pinia存储数据利用js对象：刷新就丢失，需要本地存储持久化存储一份
        SET_TOKEN(result.data as string)
        //返回一个成功的promise
        return 'ok'
      } else {
        //返回一个失败的promise
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息的方法
    async userInfo() {
      let result: userInfoReponseData = await reqUserInfo()
      // console.log(result.data.routes);
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        this.buttons = result.data.buttons
        //计算当前用户需要展示的异步路由（asyncRoute需要深拷贝一份才能使用）
        let userAsyncRoute = filterAsyncRoute(
          cloneDeep(asyncRoute),
          result.data.routes,
        )
        //整理当前用户需要的菜单数据
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute]
        //目前路由器管理的只有常量路由，其他路由需要动态注册：用户计算完毕的异步路由，任意路由需要动态追加
        ;[...userAsyncRoute, anyRoute].forEach((route: any) => {
          router.addRoute(route)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录
    async userLogout() {
      //退出登录接口(通知服务器本地用户唯一标识失效)
      let result: any = await reqLogout()
      //判断请求是否成功
      if (result.code == 200) {
        //清空仓库和本地存储的数据
        this.token = ''
        REMOVE_TOKEN()
        this.username = ''
        this.avatar = ''
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})
//对外暴露获取小仓库的方法
export default useUserStore
